// ActionScript file
import Modules.NavigationDetails;
import Modules.NavigationInfo;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.components.spinner.BusySpinner;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.DisplayModeSetter;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.events.Event;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.core.Application;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;
import mx.validators.Validator;

private var _btnEditCancel:LinkButton;

private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var taskdetails:XML;
private var _accountGUID:String = "";
private var _ni:NavigationInfo = null;

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

public function get NavInfo():NavigationInfo{
	return _ni;
}

public function set NavInfo(value:NavigationInfo):void{
	this._ni = value;
}

public function get accountGUID():String{
	return _accountGUID;
}

public function set accountGUID(value:String):void{
	this._accountGUID = value;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		DisplayModeSetter.getInstance().setMode(this.frmTaskInfo,false);
		btnSubmit.enabled = false;
		cmbAccountName.selectedItem = (taskdetails.ACCOUNTS.entry.(@id == taskdetails.RELATIONS.RELATION.(@type == "TASK_ACCOUNT"))[0]) as XML;
		lblTitle.text = "View Task Details";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		DisplayModeSetter.getInstance().setMode(this.frmTaskInfo,true);
		btnSubmit.enabled = true;
		_btnEditCancel.enabled = false;
		
		cmbAccountName.enabled = true;
		cmbAssignedTo.enabled = false;
		cmbAssignedTo.selectedItem = (taskdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		lblTitle.text = "New Task";
	}
}

private function typeSelectionChange():void{
	cmbContact.dataProvider = taskdetails.CONTACTS.entry.(@accountid == cmbAccountName.selectedItem.@id || @accountid == "0").(@active=="1" || @id == taskdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT")) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (taskdetails.CONTACTS.entry.(@id == taskdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML
}

private function windowCreated():void{

	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlTaskInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlTaskInfo.ToolBox.addChild(_btnEditCancel);
	
	this._creationCompleted = true;
	this.loadData();
	
	this.txtTaskName.setFocus();
	_btnEditCancel.enabled = CommonClass.UserLoginInfo.CanCreateTask;
}

private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
			DisplayModeSetter.getInstance().setMode(this.frmTaskInfo,true);
			btnSubmit.enabled = true;
			cmbAccountName.enabled = false;
			cmbAssignedTo.enabled = false;
			_btnEditCancel.enabled = false;
			lblTitle.text = "Edit Task Details";
			break;
	}
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	CommonClass.NextEvent = null;
	
	if(this.NavInfo!=null && this.NavInfo.sourceNavObj!=null){
		var src:NavigationDetails = (this.NavInfo.previousLink==null?null:this.NavInfo.previousLink.sourceNavObj.copy());//this.NavInfo.destinationNavObj.copy();
		var dst:NavigationDetails = this.NavInfo.sourceNavObj.copy();
		var ni:NavigationInfo = new NavigationInfo(src,dst);
		ni.previousLink = (this.NavInfo.previousLink == null? null:this.NavInfo.previousLink.previousLink);
		(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(ni);
	}else{
		(this.parentDocument as CMDWindow).loadModule();
	}
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		CommonClass.NextEvent = null;
	}
}

private function loadData():void{
	
	var params:String = "OPERATION=TASK_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) + 
						"&OWNERID="+CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForTaskDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
}

private function callForTaskDetails(event:ProcessServiceRequestResultEvent):void{
	taskdetails = XML(event.result);
	if(taskdetails.Result == "E"){
		Alert.show(taskdetails.RESPONSE.MESSAGE);
	}else if(taskdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(taskdetails);
		setScreenMode();
		typeSelectionChange();
		this.callLater(initializeForDirtyCheck);
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function setDataOnControls(response:XML):void{
	this.key = response.PKID;
	
	cmbAccountName.dataProvider = new XML(response.ACCOUNTS).entry as XMLList;
//	cmbAccountName.selectedIndex = 1;
	cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "TASK_ACCOUNT"))[0]) as XML;
	cmbAccountName.selectedIndex = (cmbAccountName.selectedIndex <0)?0:cmbAccountName.selectedIndex;
		
	cmbAssignedTo.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbAssignedTo.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	cmbAssignedTo.selectedIndex = (cmbAssignedTo.selectedIndex <0)?0:cmbAssignedTo.selectedIndex;
	
	cmbStatus.dataProvider = new XML(response.STATUS).entry as XMLList;
	cmbStatus.selectedIndex = 0;
	cmbStatus.selectedItem = (response.STATUS.entry.(@id == response.TASKSTATUSID)[0]) as XML
	
	cmbContact.dataProvider = new XML(response.CONTACTS).entry.(@accountid == cmbAccountName.selectedItem.@id || @accountid == "0").(@active=="1" || @id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT")) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (response.CONTACTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtTaskName, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	CommonClass.setDataOnComponents(this.dtStart, response);
	CommonClass.setDataOnComponents(this.dtDue, response);
	
	if(this.accountGUID!=null && this.accountGUID.length >0){
		cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@guid == this.accountGUID.toUpperCase())[0]) as XML;
	}
	
}


private function getPostData():String{
	var postData:String = new String();
	postData += "TASKID=" + (taskdetails.TASKID.toString())						+ "&";
	postData += "TASKGUID=" + (taskdetails.TASKGUID.toString())					+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
	postData += "NOTEID=" + (taskdetails.NOTEID.toString())						+ "&";
	
	postData += (CommonClass.preparePostString(this.txtTaskName))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbStatus))					+ "&";
	postData += (CommonClass.preparePostString(this.dtStart))					+ "&";
	postData += (CommonClass.preparePostString(this.dtDue))						+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbAssignedTo))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbContact));
	return postData;	
}

private function saveData(action:String, data:String=""):void{
	BusySpinner.getInstance().play(Application.application.ModuleCvs);
	var params:String = "OPERATION=TASK_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateTaskDetails);
	ws.processServiceRequest(params);
}


private function callForUpdateTaskDetails(event:ProcessServiceRequestResultEvent):void{
	var response:XML = XML(event.result);
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();

		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else{
			var ni:NavigationInfo = this.NavInfo.copy();
			ni.destinationNavObj.pkID = this.key;
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate( ni);
		}
	}else{
		BusySpinner.getInstance().stop();
		Alert.show( String(response.RESPONSE.MESSAGE) );	
	}	
	
}

private function validate():Boolean{
	var v:Array = new Array();
	v.push(nameV, accNameV);
	v.push(contactV, statusV);
	
	var result:Array = Validator.validateAll(v);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : Task Details";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}

private function initializeForDirtyCheck():void{
	BusySpinner.getInstance().stop();	
	DirtyChecker.getInstance().setInitialControl(this);
}

public function promptToSave():void{
	Alert.buttonWidth = 90;
	var yesNoCancelAlert: Alert = Alert.show("Do you want to save before exiting?", "Save",Alert.YES | Alert.NO | Alert.CANCEL, Application.application.ModuleCvs,performAlertAction);
}

private function performAlertAction(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		handleSubmitClick();
	}else if(event.detail == Alert.NO){
		DirtyChecker.getInstance().resetDirtyChecker();
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else
			handleCancelClick();
	}else{
		// PERFORM NO ACTION - STAY BACK TO THE PAGE
	}
}